/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.majiajie.pagerbottomtabstriptest.widget;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;

/**
 * 上面是半圆的自定义布局
 */
public class TabRoundLayout extends DependentLayout implements Component.EstimateSizeListener, Component.DrawTask {

    private final String CIRCLE_RADIUS = "circleRadius"; // 圆形的半径
    private final String RECTANGLE_HEIGHT = "rectangleHeight"; // 方形的高度
    private final String COLOR = "color"; // 方形的高度

    private Paint mPaint;
    private int width;
    private int height;
    private int circleRadius = 0;
    private int rectangleHeight = 0;
    private int color = 0xffffffff;

    public TabRoundLayout(Context context) {
        this(context, null);
    }

    public TabRoundLayout(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public TabRoundLayout(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init(attrSet);
    }

    private void init(AttrSet attrSet) {
        if (attrSet != null) {
            if (attrSet.getAttr(CIRCLE_RADIUS).isPresent()) {
                circleRadius = attrSet.getAttr(CIRCLE_RADIUS).get().getDimensionValue();
            }
            if (attrSet.getAttr(RECTANGLE_HEIGHT).isPresent()) {
                rectangleHeight = attrSet.getAttr(RECTANGLE_HEIGHT).get().getDimensionValue();
            }
            if (attrSet.getAttr(COLOR).isPresent()) {
                color = attrSet.getAttr(COLOR).get().getColorValue().getValue();
            }
        }
        mPaint = new Paint();
        mPaint.setColor(new Color(color));
        setEstimateSizeListener(this);
        addDrawTask(this, BETWEEN_BACKGROUND_AND_CONTENT);
    }

    @Override
    public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
        width = EstimateSpec.getSize(widthMeasureSpec);
        height = EstimateSpec.getSize(heightMeasureSpec);
        return false;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        canvas.drawRect(0, height - rectangleHeight, width, height, mPaint);
        canvas.drawCircle(width / 2, circleRadius, circleRadius, mPaint);
    }

}
